-- unload_grid
-- Created by chengb Jul/18/2015
-- 成就：拆卸格子

-- 内部函数声明
local whenUnloadGrid;

-- 注册拆卸格子的回调
EventMgr.register("achievements/unload_grid", event.UNLOAD_GRID, function(args)
    whenUnloadGrid(args);
end);

-- 注册拆卸格子的回调
whenUnloadGrid = function(args)
    local grids = args.grids;

    -- 获取当前所在的迷宫编号
    local dungeonId = DungeonM.getDungeonId();

    -- 遍历所有的子规则
    local ids = AchievementM.getIdsByRule("unload_grid");

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == AchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        if not AchievementM.isBelongTo(id, dungeonId) then
            -- 不是该迷宫的成就
            return false;
        end
        
        return true;
    end
    
    local function statGridCount(id)
        local config = AchievementM.query(id);
        local ruleArg = config["rule_arg"];
        
        local count = 0;

        if type(ruleArg) == 'table' then
            if type(ruleArg["grid_type"]) == 'number' then
                -- 统计该类型格子被拆的数量
                
                for _, grid in pairs(grids) do
                    if grid.type == ruleArg["grid_type"] then
                        count = count + 1;
                    end
                end
            end
        end
        
        return count;
    end

    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 统计被拆卸的格子数量
            local count = statGridCount(id);
            
            if count > 0 then
                -- 尝试完成成就
                AchievementM.tryComplete(id, count);
            end
        end
    end
end

return {

};